/*
 * Project: a2
 * Copyright (C) 2008 ralfoide gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*
 * -------------------------------------------
 * Original source : com.google.android.opengles.triangle/SpriteRenderer.java
 * -------------------------------------------
 *
 * Original source copyright:
 * --------------------------
 *
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.alfray.a2.engine;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.opengl.GLUtils;
import android.os.SystemClock;

import com.alfray.a2.gameplay.Cell;
import com.alfray.a2.gameplay.GameState;
import com.alfray.a2.gameplay.SpriteState;
import com.alfray.a2.gameplay.GameActivity.GameContext;

public class SpriteRenderer implements GLView.Renderer{

    private GameContext mGameContext;
    private SpriteGL mBackgroundGL;
    private SpriteGL mSpriteGL;
    private SpriteGL mBgSpriteGL;
    private int[] mTextureIds;
    private SpriteState mBgState;
    private int mCurrBgRotZ;
    private int mTextureLen;

    public SpriteRenderer(GameContext gameContext) {
        mGameContext = gameContext;
        mBackgroundGL = new SpriteGL(1, 1, 1.0f);
        mSpriteGL = new SpriteGL(1, 1, 53.0f/64.0f);
        mBgSpriteGL = null;

        mBgState = new SpriteState();
        mCurrBgRotZ = 0;
    }

    public int[] getConfigSpec() {
        // We don't need a depth buffer, and don't care about our
        // color depth.
        int[] configSpec = {
                        EGL10.EGL_DEPTH_SIZE, 0,
                        EGL10.EGL_NONE
        };
        return configSpec;
    }

    public void surfaceCreated(GL10 gl) {
        /*
         * By default, OpenGL enables features that improve quality
         * but reduce performance. One might want to tweak that
         * especially on software renderer.
         */
        gl.glDisable(GL10.GL_DITHER);

        /*
         * Some one-time OpenGL initialization can be made here
         * probably based on features of this particular context
         */
        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);

        gl.glClearColor(0, 0, 0, 1);
        //--gl.glShadeModel(GL10.GL_SMOOTH);
        //--gl.glEnable(GL10.GL_DEPTH_TEST);

        gl.glShadeModel(GL10.GL_FLAT);
        gl.glDisable(GL10.GL_DEPTH_TEST);
        gl.glEnable(GL10.GL_TEXTURE_2D);

        gl.glEnable(GL10.GL_BLEND);
        gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

        /*
         * Free previous textures if any
         */

        if (mTextureIds != null) {
            gl.glDeleteTextures(mTextureIds.length, mTextureIds, 0);
        }

        /*
         * Create our textures. This has to be done each time the
         * surface is created.
         */
        updateTextures(gl);
    }

    private void updateTextures(GL10 gl) {

        if (mTextureLen > 0 && mTextureIds != null) {
            gl.glDeleteTextures(mTextureLen, mTextureIds, 0);
        }

        Bitmap[] bitmaps = mGameContext.getThemeBitmaps();

        if (mTextureIds == null || mTextureLen != bitmaps.length) {
            mTextureLen = bitmaps.length;
            mTextureIds = new int[bitmaps.length];
        }

        gl.glGenTextures(bitmaps.length, mTextureIds, 0);

        for (int i = 0; i < bitmaps.length; i++) {
            gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[i]);

            gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
            gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

            gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
            gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

            gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
                            i == 0 ? GL10.GL_REPLACE : GL10.GL_DECAL);

            if (bitmaps[i] != null) {
                GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmaps[i], 0);
                bitmaps[i].recycle();
            }
        }
    }

    public void drawFrame(GL10 gl) {
        /*
         * By default, OpenGL enables features that improve quality
         * but reduce performance. One might want to tweak that
         * especially on software renderer.
         */
        gl.glDisable(GL10.GL_DITHER);

        gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
                        GL10.GL_MODULATE);

        /*
         * Usually, the first thing one might want to do is to clear
         * the screen. The most efficient way of doing this is to use
         * glClear().
         */

        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        /*
         * Now we're ready to draw some 3D objects
         */

        // reset model matrix
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        if (mGameContext.mNewVisualTheme != null) {
            updateTextures(gl);
            mGameContext.setNewVisualTheme(null);
        }

        // activate TMU0
        gl.glActiveTexture(GL10.GL_TEXTURE0);

        // 360 * 8 == 2880
        final long time = SystemClock.uptimeMillis() % 2880L;
        final int xAutoAngle = ((int) time) << (16 - 3);
        final int xRotZAngle = mCurrBgRotZ;

        GameState gameState = mGameContext.getState();
        final int sx = gameState.mBoardBx;
        final int sy = gameState.mBoardBy;
        Cell[] cells = gameState.mBoard;

        // draw global background
        gl.glDisable(GL10.GL_BLEND);  // backgrounds are opaque
        int texid = gameState.mSpriteBgDefault;
        int lastTexId = -1;
        if (texid >= 0) {
            gl.glPushMatrix();

            // construct the background GL sprite using the widest
            // side, which is currently SY.
            if (mBgSpriteGL == null) mBgSpriteGL = new SpriteGL(sy, sy, 1.0f);

            int x = (sy-1) << 15; //Note: x=sy/2 (and not sx) since the sprite is sy*sy
            int y = (sy-1) << 15;
            gl.glTranslatex(x, y, 0 - (2<<16));

            x = gameState.mScreenDir * (90 << 16);
            y = mCurrBgRotZ;
            if (x != y) {
                if (y > x) y -= 360<<16;
                if ((x - y) <= 180<<16) {
                    y += 10<<16;
                    if (y > x) y = x;
                } else {
                    y += 360<<16;
                    y -= 10<<16;
                    if (y < x) y = x;
                }
                mCurrBgRotZ = y;
            }
            gl.glRotatex(y, 0, 0, 1<<16);

            gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[texid]);
            lastTexId = texid;

            mBgSpriteGL.draw(gl, mBgState, 0, 0);

            gl.glPopMatrix();
        }

        // draw all backgrounds
        gl.glTranslatex(0, 0, 0 - (1<<16));
        for (int j = 0, k = 0; j < sy; j++) {
            for (int i = 0; i < sx; i++, k++) {
                Cell c = cells[k];
                SpriteState state = c.mBackground;
                texid = state.mSpriteId;
                if (state.mIsVisible && texid >= 0) {
                    if (texid != lastTexId) {
                        gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[texid]);
                        lastTexId = texid;
                    }
                    mBackgroundGL.draw(gl, state, xAutoAngle, xRotZAngle);
                }

                gl.glTranslatex(1<<16, 0, 0);
            }
            gl.glTranslatex(0 - (sx << 16), 1<<16, 0);
        }
        gl.glTranslatex(0, 0 - (sy << 16), 1<<16);

        // draw all sprites
        gl.glEnable(GL10.GL_BLEND);  // sprites are transparents
        for (int j = 0, k = 0; j < sy; j++) {
            for (int i = 0; i < sx; i++, k++) {
                Cell c = cells[k];
                SpriteState state = c.mSprite;
                texid = state.mSpriteId;
                if (state.mIsVisible && texid >= 0) {
                    if (texid != lastTexId) {
                        gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[texid]);
                        lastTexId = texid;
                    }
                    mSpriteGL.draw(gl, state, xAutoAngle, xRotZAngle);
                }

                gl.glTranslatex(1<<16, 0, 0);
            }
            gl.glTranslatex(0 - (sx << 16), 1<<16, 0);
        }

    }

    public void sizeChanged(GL10 gl, int w, int h) {
        gl.glViewport(0, 0, w, h);

        /*
         * Set our projection matrix. This doesn't have to be done
         * each time we draw, but usually a new projection needs to
         * be set when the viewport is resized.
         */

        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();

        GameState gameState = mGameContext.getState();
        final int sx = gameState.mBoardBx;
        final int sy = gameState.mBoardBy;

        int nx = w/sx;
        int ny = h/sy;
        int n = nx < ny ? nx : ny;

        float dw = (float)(w - n*sx) / 2.0f / n;
        float dh = (float)(h - n*sy) / 2.0f / n;

        gl.glOrthof(-dw - 0.5f, dw + sx - 0.5f, -dh - 0.5f, dh + sy - 0.5f, -2, 2);

    }
}

